package ru.reaperoq.routing

import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.request.*
import io.ktor.server.routing.*
import ru.reaperoq.database.Database
import ru.reaperoq.dto.CreateLocationRequest
import ru.reaperoq.dto.respondError
import ru.reaperoq.dto.respondSuccess
import ru.reaperoq.schema.UserRole
import ru.reaperoq.utils.withRole

fun Routing.locationsRouting() {
    authenticate {
        route(URLS.Locations.LOCATIONS) {
            get {
                call.respondSuccess(Database.locationsService.readAll())
            }

            post {
                withRole(UserRole.ADMIN) {
                    val body = call.receive<CreateLocationRequest>()
                    call.respondSuccess(Database.locationsService.create(body.name))
                }
            }
        }
        route(URLS.Locations.LOCATION) {
            delete {
                withRole(UserRole.ADMIN) {
                    val id = call.parameters["id"]?.toIntOrNull()
                    if (id == null) {
                        call.respondError("Неверный id")
                        return@withRole
                    }
                    Database.locationsService.delete(id)
                    call.respondSuccess(id)
                }
            }
        }
    }
}